package com.atwisdom.star.core.bsl.event;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.atwisdom.star.common.util.JsonUtil;
import com.atwisdom.star.common.util.SpringContextUtil;
import com.atwisdom.star.common.vo.ActionData;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.StatusCode;
import com.atwisdom.star.core.dao.pojo.Event;
import com.atwisdom.star.core.dao.pojo.modelClass.hier.HierInstance;
import com.atwisdom.star.core.dao.service.EventService;
import com.atwisdom.star.core.dsl.modelClass.consume.ConsumeInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.hier.HierInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.logic.LogicInstanceDslService;
import com.atwisdom.star.core.dsl.util.AutoGenUtil;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.googlecode.aviator.AviatorEvaluator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.jayway.jsonpath.JsonPath;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 1，将globalState按照name，value作为k，v的map。作为全局变量表。
 * 2，将params按照name，value作为k，v的map。
 * 3，将globalScalar按照name，value作为k，v的map。
 * 4，判断条件condition，如果condition为空，则直接运行。
 * 5，循环service进行每一步
 * 6，service中，处理scalar，按照name，value作为k，v的map。
 * 7，service中，处理state，按照每个pointer寻址并且按照path取值，存入value中，形成k，v的map
 * 8，service中，处理refs，按照引用，形成k，v的map（refs的name一定是预先规定好的，最好与方法形参同名）
 * 9，以refs的值作为传参，执行model的action方法，
 * 10，获取返回值，处理result部分·
 * 11，按照result配置，更新globalState
 * 12，service都执行完，处理back部分
 * 13，按照back的type类型，处理返回值
 */
@Slf4j
@AllArgsConstructor
@Component
public class EventUtil {
    private EventService eventService;
    private ConsumeInstanceDslService consumeInstanceDslService;
    private LogicInstanceDslService logicInstanceDslService;
    private HierInstanceDslService hierInstanceDslService;
    private AutoGenUtil autoGenUtil;

    private Map<ModelType, Function<InstancePointer, List<JSONObject>>> instanceServiceMap;

    @PostConstruct
    public void dispatcherInit(){
        instanceServiceMap.put(ModelType.Consume, (instancePointer)-> queryConsumeInstance(instancePointer));
        instanceServiceMap.put(ModelType.Logic, (instancePointer)-> queryLogicInstance(instancePointer));
        instanceServiceMap.put(ModelType.Hier, (instancePointer)-> queryHierInstance(instancePointer));
    }


    /**
     * 执行事件
     * @param category
     * @param eventExecuteBodyJson
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject execute(String category, String name, JSONObject eventExecuteBodyJson) {
        Event event = eventService.getOneByCategoryAndName(category, name);
        if (event == null) {
            throw new BusinessException(StatusCode.ERROR_DATA_ERROR.getCode(), "事件不存在");
        }
        JSONObject eventBodyJson = event.getEvent();
        handleBackDifferent(eventExecuteBodyJson, eventBodyJson);
        BeanUtil.copyProperties(eventExecuteBodyJson, eventBodyJson);
        return execute(eventBodyJson);
    }

    /**
     * 处理前端传参与后端数据结构不一样的情况，目前后台的back是json， 前端执行时，传递的参数是数组
     * @param eventExecuteBodyJson 参数中的事件执行体
     * @param eventBodyJson 数据库中的事件体
     */
    private void handleBackDifferent(JSONObject eventExecuteBodyJson, JSONObject eventBodyJson) {
        JSONArray backArray = eventExecuteBodyJson.getJSONArray("back");
        JSONObject originBackJson = eventBodyJson.getJSONObject("back");
        JSONArray originStateArray = originBackJson.getJSONArray("state");
        for (int i = 0; i < originStateArray.size(); i++) {
            JSONObject originState = originStateArray.getJSONObject(i);
            String name = originState.getString("name");
            if (CollectionUtil.isNotEmpty(backArray)) {
                backArray.forEach(backName->{
                    String s = String.valueOf(backName);
                    if (name.equals(s)) {
                        originState.put("select", true);
                    }
                });
            }

        }
        eventExecuteBodyJson.remove("back");
    }

    /**
     * 执行事件
     * @param eventExecuteBodyJson
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject execute(JSONObject eventExecuteBodyJson) {
        EventExecuteBody eventExecuteBody = build(eventExecuteBodyJson);
        List<EventInnerService> innerServiceList = eventExecuteBody.getInnerServiceList();
        // 执行事件
        innerServiceList.forEach(innerService->{
            JSONObject innerServiceJson =JsonUtil.toJSONObject(innerService);
            JSONObject globalState = eventExecuteBody.getGlobalState();
            JSONObject globalScalar = eventExecuteBody.getGlobalScalar();
            JSONObject param = eventExecuteBody.getParams();
            buildState(innerServiceJson, globalState, globalScalar, param);
            innerService = JsonUtil.toJavaBean(innerServiceJson, EventInnerService.class);
            boolean conditionResult = predicateInnerCondition(innerService, eventExecuteBody);
            if (conditionResult) {
                Object resultData = run(innerService, eventExecuteBody);
                // 需要校验是否返回成功
                // 根据返回结果，更新globalState
                JSONObject innerServiceResult = innerService.getResult();
                if (innerServiceResult.getBoolean("isResult") && resultData != null) {
                    JSONArray resultStateArray = innerServiceResult.getJSONArray("state");
                    for (int i = 0; i < resultStateArray.size(); i++) {
                        JSONObject resultStateJson = resultStateArray.getJSONObject(i);
                        String name = resultStateJson.getString("name");
                        String path = resultStateJson.getString("path");
                        if (StrUtil.isNotBlank(path) && path.startsWith("$")) {
                            Object resultValue = JsonPath.read(resultData, path);
                            // Object resultValue = JsonUtil.get(JsonUtil.toJSONObject(resultData), path);
                            eventExecuteBody.getGlobalState().put(name, resultValue);
                        } else if (JSON.isValidObject(JSONObject.toJSONString(resultData))) {
                            Object resultValue = JsonUtil.get(JsonUtil.toJSONObject(resultData), path);
                            eventExecuteBody.getGlobalState().put(name, resultValue);
                        } else if (JSON.isValidArray(JSONObject.toJSONString(resultData))) {
                            Object resultValue = JsonUtil.get(JsonUtil.toJSONArray(resultData), path);
                            eventExecuteBody.getGlobalState().put(name, resultValue);
                        } else {
                            eventExecuteBody.getGlobalState().put(name, resultData);
                        }
                        // eventExecuteBodyJson.put("globalState", eventExecuteBody.getGlobalState());
                    }
                }
            }
        });
        // 处理back
        handleBack(eventExecuteBody);
        return eventExecuteBody.getBack().getJSONObject("state");
    }

    /**
     * 处理back数据
     * @param eventExecuteBody
     *
     * back:{
     * 		isBack:true，//整个事件结束后是否需要返回值
     * 		state:[
     *             {
     *             	type:'record'//共有四种类型：record：map格式，单条记录；records：listMap格式，多条记录；map：map格式，kv组合；object：单值
     *                 name：‘’//来自globalState里的定义变量名，
     *                 value：‘’//返回值
     *             }
     * 		]
     *
     *}
     */
    private void handleBack(EventExecuteBody eventExecuteBody) {
        JSONObject resultJson = new JSONObject();
        JSONObject back = eventExecuteBody.getBack();
        if (back.getBoolean("isBack")) {
            JSONArray stateArray = back.getJSONArray("state");
            for (int i = 0; i < stateArray.size(); i++) {
                JSONObject stateJson = stateArray.getJSONObject(i);
                String name = stateJson.getString("name");
                Boolean selectFlag = stateJson.getBoolean("select");
                if (selectFlag != null && selectFlag) {
                    // stateJson.put(name, eventExecuteBody.getGlobalState().get(name));
                    // stateArray.set(i, stateJson);
                    resultJson.put(name, eventExecuteBody.getGlobalState().get(name));
                }
            }
            // back.put("state", stateArray);
            back.put("state", resultJson);
        }
    }


    /**
     * 构建一个事件执行时的对象主体，即：EventExecuteBody
     * @param eventExecuteBodyJson
     * @return
     */
    public EventExecuteBody build(JSONObject eventExecuteBodyJson) {
        buildGlobalScalar(eventExecuteBodyJson);
        buildGlobalState(eventExecuteBodyJson);
        buildParam(eventExecuteBodyJson);
        JSONArray innerServiceJsonArray = eventExecuteBodyJson.getJSONArray("service");
        for (int i = 0; i < innerServiceJsonArray.size(); i++) {
            JSONObject eventInnerServiceJson = innerServiceJsonArray.getJSONObject(i);
            buildScalar(eventInnerServiceJson);
        }
        boolean conditionStatus = predicateCondition(eventExecuteBodyJson);
        EventExecuteBody eventExecuteBody = JsonUtil.toJavaBean(eventExecuteBodyJson, EventExecuteBody.class);
        List<EventInnerService> eventInnerServiceList = buildInnerServiceList(eventExecuteBodyJson);
        eventExecuteBody.setConditionStatus(conditionStatus);
        eventExecuteBody.setInnerServiceList(eventInnerServiceList);
        return eventExecuteBody;
    }

    /**
     * 将globalState按照name，value作为k，v的map。作为全局变量表
     */
    private JSONObject buildGlobalState(JSONObject eventExecuteJson) {
        JSONArray globalStateArray = eventExecuteJson.getJSONArray("globalState");
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < globalStateArray.size(); i++) {
            JSONObject globalState = globalStateArray.getJSONObject(i);
            String name = globalState.getString("name");
            Object value = globalState.get("value");
            resultJson.put(name, value);
        }
        eventExecuteJson.put("globalState", resultJson);
        return resultJson;
    }

    /**
     * 将params按照name，value作为k，v的map
     * @return
     */
    public JSONObject buildParam(JSONObject eventExecuteJson) {
        JSONObject globalScalar = eventExecuteJson.getJSONObject("globalScalar");
        JSONObject globalState = eventExecuteJson.getJSONObject("globalState");
        JSONArray state = eventExecuteJson.getJSONArray("state");
        JSONObject scalar = eventExecuteJson.getJSONObject("scalar");
        JSONArray paramArray = eventExecuteJson.getJSONArray("params");
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject param = paramArray.getJSONObject(i);
            String name = param.getString("name");
            Object value = param.get("value");
            if (value instanceof List) {
                JSONArray valueArray = handleParamValueVariable(globalScalar, globalState, param, value, state, scalar);
                resultJson.put(name, valueArray);
            } else if (String.valueOf(value).contains("${")) {
                value = handleVariable(String.valueOf(value), globalState, globalScalar, param, state, scalar);
                if (value != null) {
                    resultJson.put(name, value);
                }
            } else {
                resultJson.put(name, value);
            }
        }
        autoGenUtil.handleAutoGenValue(resultJson);
        eventExecuteJson.put("params", resultJson);
        return resultJson;
    }


    /**
     * 处理data为array的情况
     * @param globalScalar
     * @param globalState
     * @param param
     * @param value
     * @return
     */
    private JSONArray handleParamValueVariable(JSONObject globalScalar, JSONObject globalState, JSONObject param, Object value, JSONArray state, JSONObject scalar) {
        JSONArray valueArray = JsonUtil.toJSONArray(value);
        valueArray.forEach(d->{
            if (d instanceof JSONObject) {
                handleJsonObject(globalScalar, globalState, param, (JSONObject) d, state, scalar);
            }
        });
        return valueArray;
    }

    /**
     * 处理value为json的情况
     * @param globalScalar
     * @param param
     * @param d
     */
    private void handleJsonObject(JSONObject globalScalar, JSONObject globalState, JSONObject param, JSONObject d, JSONArray state, JSONObject scalar) {
        d.forEach((k, v)->{
            if (String.valueOf(v).contains("${")) {
                if (v instanceof JSONObject) {
                    handleJsonObject(globalScalar, globalState, param, (JSONObject)v, state, scalar);
                } else {
                    v = handleVariable(String.valueOf(v), globalState, globalScalar, param, state, scalar);
                }
                if (!"".equals(String.valueOf(v))) {
                    d.put(k, v);
                }
            }
        });
    }

    /**
     * 将globalScalar按照name，value作为k，v的map
     * @return
     */
    public JSONObject buildGlobalScalar(JSONObject eventExecuteJson) {
        JSONArray globalScalarArray = eventExecuteJson.getJSONArray("globalScalar");
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < globalScalarArray.size(); i++) {
            JSONObject globalScalar = globalScalarArray.getJSONObject(i);
            String name = globalScalar.getString("name");
            Object value = globalScalar.get("value");
            resultJson.put(name, value);
        }
        autoGenUtil.handleAutoGenValue(resultJson);
        eventExecuteJson.put("globalScalar", resultJson);
        return JsonUtil.toJSONObject(resultJson);
    }

    /**
     * 判断条件condition，如果condition为空，则直接运行
     * @return
     */
    public boolean predicateCondition(JSONObject eventExecuteBodyJson) {
        String condition = eventExecuteBodyJson.getString("condition");
        if (StrUtil.isBlank(condition)) {
            return true;
        }
        Object execute = AviatorEvaluator.execute(condition);
        return Boolean.valueOf(String.valueOf(execute));
    }

    /**
     * 判断条件condition，如果condition为空，则直接运行
     * @return
     * **/
    public boolean predicateInnerCondition(EventInnerService eventInnerService, EventExecuteBody eventExecuteBody) {
        String innerCondition = eventInnerService.getCondition();
        if (StrUtil.isBlank(innerCondition)) {
            return true;
        }
        JSONObject globalState = eventExecuteBody.getGlobalState();
        JSONObject globalScalar = eventExecuteBody.getGlobalScalar();
        JSONArray state = eventInnerService.getState();
        JSONObject scalar = eventInnerService.getScalar();

        // 处理param中也有引用的情况
        JSONObject param = eventExecuteBody.getParams();
        param = handleParam(param, globalState, globalScalar, state, scalar);

        // 获取数据，进行替换
        if (innerCondition.contains("${")) {
            innerCondition = String.valueOf(handleVariable(innerCondition, globalState, globalScalar, param, state, scalar));
        }
        log.info("innerCondition = {}", innerCondition);
        if (StrUtil.isBlank(innerCondition) || innerCondition.equals("null")) {
            return false;
        }
        if (innerCondition.equals("null == nil") || innerCondition.equals(" == ''") || innerCondition.equals("null == ''")) {
            return true;
        }
        if (innerCondition.equals("null != nil") || innerCondition.equals(" != ''")) {
            return false;
        }
        // 包含空的，计算表达式会出错，手动处理
        // if (innerCondition.contains("null")) {
        //     return innerCondition.startsWith("!") ? true : false;
        // }
        Object execute = AviatorEvaluator.execute(innerCondition);
        return Boolean.valueOf(String.valueOf(execute));
    }

    /**
     * 构建一个事件service主体
     * @param eventExecuteBodyJson
     * @return
     */
    public List<EventInnerService> buildInnerServiceList(JSONObject eventExecuteBodyJson) {
        ArrayList<EventInnerService> innerServiceList = new ArrayList<>();
        JSONArray innerServiceJsonArray = eventExecuteBodyJson.getJSONArray("service");
        for (int i = 0; i < innerServiceJsonArray.size(); i++) {
            JSONObject eventInnerServiceJson = innerServiceJsonArray.getJSONObject(i);
            // buildState(eventInnerServiceJson);
            // buildScalar(eventInnerServiceJson);
            // buildRefs(eventInnerServiceJson, eventExecuteBodyJson);
            EventInnerService innerService = JsonUtil.toJavaBean(eventInnerServiceJson, EventInnerService.class);
            innerServiceList.add(innerService);
        }
        return innerServiceList;
    }


    /**
     * 将state按照name，value作为k，v的map。作为变量表
     * @param eventInnerServiceJson
     * @return
     */
    private JSONArray buildState(JSONObject eventInnerServiceJson, JSONObject globalState,
                                    JSONObject globalScalar, JSONObject param) {
        JSONObject scalar = eventInnerServiceJson.getJSONObject("scalar");
        JSONArray stateArray = eventInnerServiceJson.getJSONArray("state");
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < stateArray.size(); i++) {
            JSONObject state = stateArray.getJSONObject(i);
            String name = state.getString("name");
            Object value = state.get("value");
            Object pointerJson = state.get("pointer");
            // pointer : ${param.pointer1}
            if (ObjectUtil.isNotNull(pointerJson) && pointerJson instanceof String) {
                // 获取数据，进行替换
                String pointerStr = JSON.toJSONString(pointerJson);
                if (pointerStr.contains("${")) {
                    pointerJson = handleVariable(pointerStr, globalState, globalScalar, param, stateArray, scalar);
                }
                // pointerJson = JSONObject.parseObject(pointerStr);
            }
            InstancePointer pointer = JsonUtil.toJavaBean(JsonUtil.toJSONObject(pointerJson), InstancePointer.class);
            if (ObjectUtil.isNotNull(pointer)) {
                List<JSONObject> instanceDataList = fetchDataFromInstance(pointer);
                String path = state.getString("path");
                if (StrUtil.isNotBlank(path)) {
                    value = JsonUtil.get(JsonUtil.toJSONArray(instanceDataList), path);
                }
            }
            state.put("value", value);
        }
        return stateArray;
    }

    /**
     * 将Scalar按照name，value作为k，v的map。作为常量表
     * @param eventInnerServiceJson
     * @return
     */
    private JSONObject buildScalar(JSONObject eventInnerServiceJson) {
        JSONArray scalarArray = eventInnerServiceJson.getJSONArray("scalar");
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < scalarArray.size(); i++) {
            JSONObject scalar = scalarArray.getJSONObject(i);
            String name = scalar.getString("name");
            Object value = scalar.get("value");
            resultJson.put(name, value);
        }
        autoGenUtil.handleAutoGenValue(resultJson);
        eventInnerServiceJson.put("scalar", resultJson);
        return resultJson;
    }

    /**
     * 组装refs
     * @param eventInnerService innerService 对象
     * @param eventExecuteBody 事件主体
     * @return
     */
    private JSONObject buildRefs(EventInnerService eventInnerService, EventExecuteBody eventExecuteBody) {
        JSONObject globalState = eventExecuteBody.getGlobalState();
        JSONObject globalScalar = eventExecuteBody.getGlobalScalar();
        JSONArray stateArray = eventInnerService.getState();
        JSONObject scalar = eventInnerService.getScalar();

        // 处理param中也有引用的情况
        JSONObject param = eventExecuteBody.getParams();
        param = handleParam(param, globalState, globalScalar, stateArray, scalar);

        JSONArray refArray = eventInnerService.getRefs();
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < refArray.size(); i++) {
            JSONObject ref = refArray.getJSONObject(i);
            String name = ref.getString("name");
            Object value = ref.get("value");
            // 获取数据，进行替换
            if (String.valueOf(value).contains("${")) {
                value = handleVariable(String.valueOf(value), globalState, globalScalar, param, stateArray, scalar);
            }
            if ("data".equals(name)) {
                System.out.println(value);
                value = JsonUtil.toJSONArray(value);
            }

            if (JSONObject.isValidObject(String.valueOf(value))) {
                value = JSONObject.parseObject(String.valueOf(value));
            }
            if (JSONObject.isValidArray(String.valueOf(value))) {
                value = JSONObject.parseArray(String.valueOf(value));
            }
            resultJson.put(name, value);
        }
        // eventInnerServiceJson.put("refs", resultJson);
        return resultJson;
    }

    /**
     * 处理变量，并返回变量的值
     * @param valuePointer
     * @return
     */
    public Object handleVariable(String valuePointer, JSONObject globalState ,
                                 JSONObject globalScalar,
                                 JSONObject param,
                                 JSONArray state,
                                 JSONObject scalar) {
        Pattern pattern = Pattern.compile("\\$\\{(.*?)\\}");
        Matcher matcher = pattern.matcher(valuePointer);
        List<String> matches = new ArrayList<>();
        while (matcher.find()) {
            matches.add(matcher.group(1));
        }
        Object value = valuePointer;
        // 存在一个语句中有多个$的情况
        if (CollectionUtil.isNotEmpty(matches)) {
            if (matches.size() == 1) {
                String match = matches.get(0);
                value = fetchRefValue(valuePointer, match,
                        globalState, globalScalar, param, state, scalar);
            } else {
                matches = matches.stream().distinct().collect(Collectors.toList());
                for (String match : matches) {
                    value = fetchRefValue(String.valueOf(value), match,
                            globalState, globalScalar, param, state, scalar);
                    value = String.valueOf(value);
                }
            }
        }
        return value;
    }

    /**
     *
     * 根据引用的key，得到引用的值
     * @param valuePointer
     * @param matchPointer 匹配的指针
     * @param globalState
     * @param globalScalar
     * @param param
     * @param stateArray 因为state在执行过程中，要动态的查询数据，所以后续必须保留pointer，不能只有name,value,所以设置成了数组
     * @param scalar
     * @return
     */
    private Object fetchRefValue(String valuePointer, String matchPointer, JSONObject globalState ,
        JSONObject globalScalar,
        JSONObject param,
        JSONArray stateArray,
        JSONObject scalar) {
        Object value = valuePointer;
        boolean replaceFlag = false;
        if (matchPointer.startsWith("globalState")) {
            value = JsonUtil.get(globalState, matchPointer.substring(matchPointer.indexOf(".")+1));
            replaceFlag = true;
        } else if (matchPointer.startsWith("globalScalar")) {
            value = JsonUtil.get(globalScalar, matchPointer.substring(matchPointer.indexOf(".")+1));
            replaceFlag = true;
        } else if (matchPointer.startsWith("params")) {
            value = JsonUtil.get(param, matchPointer.substring(matchPointer.indexOf(".")+1));
            replaceFlag = true;
        } else if (matchPointer.startsWith("state")) {
            String tempMatchPointer = matchPointer.substring(matchPointer.indexOf(".") + 1);
            for (int j = 0; j < stateArray.size(); j++) {
                JSONObject state = stateArray.getJSONObject(j);
                if (state.getString("name").equals(tempMatchPointer)) {
                    value = state.get("value");
                }
            }
            replaceFlag = true;
        } else if (matchPointer.startsWith("scalar")) {
            value = JsonUtil.get(scalar, matchPointer.substring(matchPointer.indexOf(".")+1));
            replaceFlag = true;
        }

        if (!(value instanceof Map) && !(value instanceof JSONArray) && replaceFlag) {
            value = valuePointer.replace("${" + matchPointer + "}", String.valueOf(value));
        }
        return value;
    }

    /**
     * 执行方法
     * @return
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public Object run(EventInnerService eventInnerService, EventExecuteBody eventExecuteBody){
        try {
        // EventExcuteActionType eventExcuteActionType = EventExcuteActionType.valueOf("Business");
        ServiceEnum serviceEnum = ServiceEnum.valueOf(eventInnerService.getModel());
        Object service = SpringContextUtil.getBean(serviceEnum.getServiceId());
        // BusinessBslServiceImpl businessBslService = SpringContextUtil.getBean("businessBslServiceImpl", BusinessBslServiceImpl.class);

            Object resultInfo = null;
            Object refJson = buildRefs(eventInnerService, eventExecuteBody);
            Method[] methods = service.getClass().getDeclaredMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                if (method.getName().equals(eventInnerService.getAction()) && method.getParameterCount() <= 1) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    if (method.getParameterCount() == 0) {
                        resultInfo = method.invoke(service);
                    } else {
                        if (parameterTypes[0] == ActionData.class) {
                            ActionData<JSONObject> actionData = new ActionData<>();
                            BeanUtil.copyProperties(refJson, actionData);
                            resultInfo = method.invoke(service, actionData);
                        } else {
                            resultInfo = method.invoke(service,refJson);
                            // resultInfo = method.invoke(service, parameterTypes[0].cast(refJson));
                        }
                    }
                    break;
                }
                if (i == methods.length - 1) {
                    log.error("调用的方法不存在, 方法名：{}", eventInnerService.getAction());
                    throw new BusinessException("调用的方法不存在");
                }
            }

            // if (eventExecuteActionType.getParameterType() == 2) {
            //     Method method = service.getClass().getMethod(eventInnerService.getAction(), JSONObject.class);
            //     resultInfo = method.invoke(service, refJson);
            // } else {
            //     Method method = service.getClass().getMethod(eventInnerService.getAction(), ActionData.class);
            //     ActionData<JSONObject> actionData = new ActionData<>();
            //     BeanUtil.copyProperties(refJson, actionData);
            //     resultInfo = method.invoke(service, actionData);
            // }
            return resultInfo;
        } catch (InvocationTargetException e) {
            log.error("调用方法出错, {}", e);
            throw new BusinessException(e.getCause().getMessage());
        } catch (IllegalAccessException e) {
            log.error("没有访问该方法权限");
            throw new BusinessException(e);
        }
    }

    /**
     * 从数据库中查询结果
     * @param pointer
     */
    private List<JSONObject> fetchDataFromInstance(InstancePointer pointer){
        ModelType modelType = ModelType.getByCode(pointer.getModel());
        return instanceServiceMap.get(modelType).apply(pointer);
    }

    /**
     * 查询实例数据
     * 应该有一个公共的接口，这样可以把类似方法合成一个方法，能简单不少。
     * @param instancePointer
     * @return
     */
    private List<JSONObject>  queryConsumeInstance(InstancePointer instancePointer) {
        String condition = instancePointer.getCondition();
        String className = instancePointer.getClassName();
        List<JSONObject> dataList = consumeInstanceDslService.query(condition, className, null);
        return dataList;
    }

    /**
     * 查询实例数据
     * @param instancePointer
     * @return
     */
    private List<JSONObject>  queryLogicInstance(InstancePointer instancePointer) {
        String condition = instancePointer.getCondition();
        String className = instancePointer.getClassName();
        List<JSONObject> dataList = logicInstanceDslService.query(condition, className);
        return dataList;
    }
    /**
     * 查询实例数据
     * @param instancePointer
     * @return
     */
    private List<JSONObject>  queryHierInstance(InstancePointer instancePointer) {
        String containerModel = instancePointer.getContainerModel();
        String condition = instancePointer.getCondition();
        String className = instancePointer.getClassName();
        List<HierInstance> list = hierInstanceDslService.query(containerModel, className, condition);
        List<JSONObject> dataList = list.stream().map(d->JsonUtil.toJSONObject(d)).collect(Collectors.toList());

        return dataList;
    }

    public JSONObject handleParam(JSONObject param, JSONObject globalState,
                                  JSONObject globalScalar,
                                  JSONArray state,
                                  JSONObject scalar) {
        String s = JSON.toJSONString(param);
        Object handleValue = handleVariable(s, globalState, globalScalar, param, state, scalar);
        param = JSON.parseObject(handleValue.toString());
        return param;
    }
}